Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve livechat parser & add remaining action nodes #285

Merged
merged 4 commits into from
Jan 10, 2023

Conversation

LuanRT
Copy link
Owner

@LuanRT LuanRT commented Jan 10, 2023

Description

The live chat parser was missing quite a lot of nodes and some of the typings were incorrect too, this PR should fix that. Also, 2 new events were added: end and error.

  • end: Fired when the livestream ends.
  • error: Fired when something goes wrong while polling the API. Note that if an error occurs, it will retry indefinitely unless LiveChat#stop() is called.

And lastly, this also adds support for filtering the live chat:

// The live chat will restart by itself to apply the filter if required
livechat.applyFilter('LIVE_CHAT'); // can be LIVE_CHAT or TOP_CHAT

A working usage example:

import { Innertube, UniversalCache, YTNodes } from 'youtubei.js';
import { LiveChatContinuation } from 'youtubei.js/dist/src/parser';
import { ChatAction, LiveMetadata } from 'youtubei.js/dist/src/parser/youtube/LiveChat';

(async () => {
  const yt = await Innertube.create({ cache: new UniversalCache(), generate_session_locally: true });

  const search = await yt.search('lofi hip hop radio - beats to relax/study to');
  const info = await yt.getInfo(search.videos[0].as(YTNodes.Video).id);

  const livechat = info.getLiveChat();

  livechat.on('start', (initial_data: LiveChatContinuation) => {
    /**
     * Initial info is what you see when you first open a a live chat — this is; initial actions (pinned messages, top donations..), account's info and so forth.
     */
    console.info(`Hey ${initial_data.viewer_name || 'Guest'}, welcome to Live Chat!`);

    const pinned_action = initial_data.actions.firstOfType(YTNodes.AddBannerToLiveChatCommand);

    if (pinned_action) {
      if (pinned_action.banner?.contents?.is(YTNodes.LiveChatTextMessage)) {
        console.info(
          '\n', 'Pinned message:\n',
          pinned_action.banner.contents.author?.name.toString(), '-', pinned_action?.banner.contents.message.toString(),
          '\n'
        );
      }
    }
  });

  livechat.on('error', (error: Error) => console.info('Live chat error:', error));

  livechat.on('end', () => console.info('This live stream has ended.'));

  livechat.on('chat-update', (action: ChatAction) => {
    /**
     * An action represents what is being added to
     * the live chat. All actions have a `type` property,
     * including their item (if the action has an item).
     *
     * Below are a few examples of how this can be used.
     */

    if (action.is(YTNodes.AddChatItemAction)) {
      const item = action.as(YTNodes.AddChatItemAction).item;

      if (!item)
        return console.info('Action did not have an item.', action);

      const hours = new Date(item.hasKey('timestamp') ? item.timestamp : Date.now()).toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit'
      });

      switch (item.type) {
        case 'LiveChatTextMessage':
          console.info(
            `${item.as(YTNodes.LiveChatTextMessage).author?.is_moderator ? '[MOD]' : ''}`,
            `${hours} - ${item.as(YTNodes.LiveChatTextMessage).author?.name.toString()}:\n` +
            `${item.as(YTNodes.LiveChatTextMessage).message.toString()}\n`
          );
          break;
        case 'LiveChatPaidMessage':
          console.info(
            `${item.as(YTNodes.LiveChatPaidMessage).author?.is_moderator ? '[MOD]' : ''}`,
            `${hours} - ${item.as(YTNodes.LiveChatPaidMessage).author.name.toString()}:\n` +
            `${item.as(YTNodes.LiveChatPaidMessage).message.toString()}\n`,
            `${item.as(YTNodes.LiveChatPaidMessage).purchase_amount}\n`
          );
          break;
        case 'LiveChatPaidSticker':
          console.info(
            `${item.as(YTNodes.LiveChatPaidSticker).author?.is_moderator ? '[MOD]' : ''}`,
            `${hours} - ${item.as(YTNodes.LiveChatPaidSticker).author.name.toString()}:\n` +
            `${item.as(YTNodes.LiveChatPaidSticker).purchase_amount}\n`
          );
          break;
        default:
          console.debug(action);
          break;
      }
    }

    if (action.is(YTNodes.AddBannerToLiveChatCommand)) {
      console.info('Message pinned:', action.banner?.contents);
    }

    if (action.is(YTNodes.RemoveBannerForLiveChatCommand)) {
      console.info(`Message with action id ${action.target_action_id} was unpinned.`);
    }

    if (action.is(YTNodes.RemoveChatItemAction)) {
      console.warn(`Message with action id ${action.target_item_id} just got deleted!`, '\n');
    }
  });

  livechat.on('metadata-update', (metadata: LiveMetadata) => {
    console.info(`
      VIEWS: ${metadata.views?.view_count.toString()}
      LIKES: ${metadata.likes?.default_text}
      DATE: ${metadata.date?.date_text}
    `);
  });

  livechat.start();
})();

Closes #282

PS: sorry for the large diff :×

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • This change requires a documentation update

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have checked my code and corrected any misspellings

@github-actions github-actions bot added the tests label Jan 10, 2023
@LuanRT LuanRT marked this pull request as ready for review January 10, 2023 04:42
@LuanRT LuanRT merged commit 8e37efa into main Jan 10, 2023
@LuanRT LuanRT deleted the refactor/improve-livechat-parser branch January 10, 2023 04:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Improve live chat's initial data parsing
1 participant